# -*- coding: utf-8 -*-
#autor: João Rebocho Nº 6035
#Data:20/10/2013
#obs: Aula prática 6
#Exemplos do livro

#1ºExemplo
import threading

#variavel global acedida pelas threads
theVar = 1

class MyThread(threading.Thread):
	def run(self):
		global theVar
		print 'Esta e a thread'  + str(theVar) + 'falando.'
		print 'Ola e adeus'
		theVar = theVar + 1
		pass 
	pass 
	
for x in xrange(20):
	MyThread().start()

#Segundo Exemplo
#Versao sequencial

import os
import re
import time
import sys
from threading import Thread 

lifeline = re.compile(r"(\d) received")
report = ("No response", "Partial Response", "Alive")
print time.ctime()

for host in range(10, 30):
	ip = "10.30.170." + str(host)
	pingaling = os.popen("ping -q -c2"+ip, "r")
	print "Testing", ip, sys.stdout.flush()
	while 1:
		line = pingaling.readline()
		if not line: break
		igot = re.findall(lifeline, line)
		if igot:
			print report[int(igot[0])]
	pass 
print time.ctime()

class testit(Thread):
	def __init__(self, ip):
		Thread.__init__(self)
		self.ip = ip
		self.status = -1
		pass 
	
	def run(self):
		pingaling = os.popen("ping -q -c2"+ self.ip, "r")
		while 1:
			line = pingaling.readline()
			if not line: break
			igot = re.findall(testit.lifeline, line)
			if igot:
				self.status = int(igot[0])
		pass
	pass  
		
testit.lifeline = re.compile(r"(\d) received")
report = ("No response","Partial Response", "Alive")

print time.ctime()

pinglist = []

for host in range(10, 30):
	ip = "10.30.170."+str(host)
	current = testit(ip)
	pinglist.append(current)
	current.start()

for pingle in pinglist:
	pingle.join()
	print "Status from", pingle.ip, "is", report[pingle.status]
	
print time.ctime()

#Terceiro Exemplo
import urllib2

hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com", "http://ibm.com", "http://apple.com"]
start = time.time()
#grabs urls of hosts and prints first 1024 bytes of page
for host in hosts:
	url = urllib2.urlopen(host)
	print url.read(1024)
	
print "Elapsed Time: %s" %(time.time() -start)

import Queue
hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com", "http://ibm.com", "http://apple.com"]
queue = Queue.Queue()

class ThreadUrl(threading.Thread):
	''' Threaded Url Grab'''
	def __init__(self, queue):
		threading.Thread.__init__(self)
		self.queue = queue
		pass 
	
	def run(self):
		while True:
			#grabs host from queue
			host = self.queu.get()
			
			#grabs urls of hosts and prints first 1024 bytes of page
			url = urllib2.urlopen(host)
			print url.read(1024)
			
			#signals to queue job is done
			self.queue.task_done()
start  = time.rime()
def main():
	#spawn a pool of threads, and pass them queue instance
	for i in range(3):
		t = TreadUrl(queue)
		t.setDaemon(True)
		t.start()
		
	#populate queue with data
	for host in hosts:
		queue.put(host)
	
	#wait on the queue until everything has been processed
	queue.join()
main()
print "Elapsed Time: %s" %(time.time() -start)			
